<?php

namespace App\Process;

use App\Model\FormidsChunqiuModel;
use App\Utility\RedisTools;
use EasySwoole\EasySwoole\Swoole\Process\AbstractProcess;

class FormId extends AbstractProcess{
    private $isRun = false;
    public function run($arg){
        //定时500ms检测有没有任务，有的话就while死循环执行
        $this->addTick(500,function (){
            if(!$this->isRun){
                $this->isRun = true;
                go(function (){
                    while (true){
                        try{
                            $queue = new RedisTools($this->getProcessName());
                            $task = $queue->read();
                            if($task){
                                //不同的openid生成不同的formid集合，并记录有效时间
                                $queue->zAdd($task['openid'],$task['expire'],$task['formid']);
                                //不同的小程序生成不同的openid集合
                                $queue->sAdd($task['name'],$task['name'].'*'.$task['openid']);
                                //记录数据库用作备份资料
                                $model  = new FormidsChunqiuModel();
                                $insert = [
                                    'openid' => $task['openid'],
                                    'expires_at' => $task['expire'],
                                    'formid' => $task['formid'],
                                ];
                                $model->create($insert);
                                unset($model);
                            }else{
                                break;
                            }
                            unset($queue);
                        }catch (\Throwable $throwable){
                            break;
                        }
                    }
                    $this->isRun = false;
                });
            }
        });
    }

    public function onShutDown()
    {
        // TODO: Implement onShutDown() method.
    }

    public function onReceive(string $str, ...$args)
    {
        // TODO: Implement onReceive() method.
    }
}
